<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('purchaseReturn.pageTitle')" scanType="1" @clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto-noheight paddingbottom">
				<!-- 调拨单信息 -->
				<view class="custom-form-card" v-if="data.wmsInStockInfo">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('purchaseReturn.generateInfo') }}
					</view>
					<view class="custom-card-itemOne">
						<!-- <text class="item-info-title">{{ $t('purchaseReturn.generateOrder') }}：</text>{{data.wmsInStockInfo.poCode || data.wmsInStockInfo.voCode }} -->
						<text  class="item-info-title" v-if="data.wmsInStockInfo.poCode ">{{ $t('purchaseReturn.returnOrderNo') }}：
							<text style="color: black;">{{ data.wmsInStockInfo.poCode }}</text>
						</text>
						<text  class="item-info-title" v-else>{{ $t('purchaseReturn.voucherNo') }}：
							<text style="color: black;">{{ data.wmsInStockInfo.voCode }}</text>
						</text>
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('hardware.receiptsQty') }}：</text>{{
							data.wmsInStockInfo.sumQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('months.qtyToReturn') }}：</text>{{
							data.wmsInStockInfo.returnTotalQty-data.wmsInStockInfo.scannedQuantity }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity') }}：</text>{{
							data.wmsInStockInfo.scannedQuantity }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('purchaseReturn.generateDate') }}：</text>{{
							data.wmsInStockInfo.returnDate }}
					</view>
				</view>
				<!-- 扫描条码 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-scan">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>
				<!-- 当前扫描条码 -->
				<view class="custom-form-card" v-if="data.currentScanInfo">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
										data.currentScanInfo.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
										data.currentScanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
										data.currentScanInfo.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
											data.currentScanInfo.unit }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>
										{{ data.currentScanInfo.currentQty }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('purchaseReturn.generateInfo') }}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 300rpx">
						<zb-table :columns="data.column" :stripe="true" @rowClick="rowClick" :border="true"
							:data="data.wmsInstockDs" :cell-style="cellStyle" :cell-header-style="cellHeaderStyle"
							@customLook="customBtnFn">
						</zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCreatOrder">
						{{ $t('purchaseReturn.generateSheet') }}
					</view>
				</view>
			</view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" type="center">
				<view v-if="data.wmsReceiptDsInfo" class="input-dialog-box"
					style="padding: 40rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
							data.wmsReceiptDsInfo.materialCode }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
							data.wmsReceiptDsInfo.materialName }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
							data.wmsReceiptDsInfo.materialSpec }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
							data.wmsReceiptDsInfo.unit }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('hardware.receiptsQty') }}：</text>{{
							data.wmsReceiptDsInfo.sumQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity') }}：</text>{{
							data.wmsReceiptDsInfo.scanNum }}
					</view>
				</view>
			</uni-popup>
			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}：{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
						</view>
						<view class="gui-form-item">
							<text>{{ $t('distributedEnter.qty') }}：</text>
							<view>
								<input type="number" style="margin: 8rpx 0;" class="gui-form-input"
									v-model="data.scanInfo.currentQty"
									:placeholder="$t('distributedEnter.pleaseMaterialQty')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('calendar.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
							{{ $t('calendar.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import { wmsInStockInfoById, wmsSelectWmsBarcodeInfo, commitRefund } from '@/api/api.js'
import { ref, reactive, toRaw, watch, computed, onMounted } from 'vue';
import { useStore } from "vuex";
import tableColor from '@/hooks/tableColor.js';
import { sortClass } from '@/utils/index.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import { onBackPress } from '@dcloudio/uni-app';
//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let { tableData } = tableColor();
const { scan } = pdaScan()
let store = useStore();
const { cellStyle, cellHeaderStyle } = tableColor();
// 接受来自父组件的传参 页面传值
const props = defineProps({
	poCode: String,
	voCode: String,
	returnTypeId: String,
});
let popup = ref(null);
let inputDialog = ref(null);
let data = reactive({
	wmsInStockInfo: undefined,// 推料信息
	wmsInstockDs: [],// 物料信息
	poCode: props.poCode, // 上级界面传过来
	voCode: props.voCode,// 上级界面传过来的
	returnTypeId: props.returnTypeId,// 上级界面传过来的
	scanInfo: undefined,
	wmsReceiptDsInfo: {},//查看展示info
	wmsInstockDs: [],
	currentScanInfo: undefined,// 当前扫描信息
	scanValue: '',// 扫描的条码号
	currentQty: null,// 扫码输入的数量
	scanList: [],
	sumQty: 0,//能退的最大总量
	value: ['0'],
	selectedOut: '爱丽',
	selectedEnter: '美国',
	inputValue: '',
	column: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 80,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		width: 100,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
	},
	{
		name: 'materialSpec',
		label: t('distributedEnter.materialSpec')
	},
	{
		name: 'unit',
		label: t('distributedEnter.uom'),
	},
	{
		name: 'qty',
		label: t('hardware.receiptsQty')
	},
	{
		name: 'returnQty',
		label: t('pageTranslation.retiredNumber')
	},
	{
		name: 'scanNum',
		label: t('distributedEnter.scannedQuantity'),
		width: 120,
	}
	]
})
onMounted(() => {
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getRequestData()
})
// fqc扫描条码
data.scanList = computed(() => {
	return store.state.stockManage.wmsReturnScanList
})
const watcShowscanList = () => {
	if (!data.wmsInStockInfo) return
	var newVal = data.scanList
	//计算 初始化数量 
	let scannedQuantity = newVal.reduce(function (prev, cur) {
		return prev + Number(cur.currentQty);
	}, 0)
	// 当前无本地记录扫码数据 但有历史记录手动赋值本地扫码信息
	if (!data.currentScanInfo && newVal.length > 0) {
		data.currentScanInfo = newVal[0]
	}
	// 当前有本地记录扫码数据 但无历史记录手动置空本地扫码信息
	if (data.currentScanInfo && newVal.length == 0) {
		data.currentScanInfo = undefined
	}
	// 遍历数组 查询当前扫描的物料信息 与当前的收集单信息相比对进行重新赋值
	data.wmsInstockDs.forEach(element => {
		let scanNum = 0
		newVal.forEach(item => {
			// 根据当前扫描的materialCode物料code  查询到相对应收集单信息
			if (element.materialCode == item.materialCode) {
				scanNum = scanNum + Number(item.currentQty)
			}
		});
		element.scanNum = scanNum //物料数量
	});
	data.wmsInStockInfo.scannedQuantity = scannedQuantity //入库单信息数量修改
}
//把扫描条码变为物料集合的二维数组
watch(() => data.scanList, (newVal) => {
	watcShowscanList()
}, {
	immediate: true,
	deep: true
});

// 查询初始化数据
const getRequestData = () => {
	let parmes = {
		poCode: data.poCode == 'null' ? '' : data.poCode,
		voCode: data.voCode == 'null' ? '' : data.voCode,
		returnType: data.returnTypeId == 'null' ? '' : data.returnTypeId,
		current: 1,
		size: 10,
		isSp: 'N',
	}
	wmsInStockInfoById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_LOOK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			console.log(res.data)
			data.wmsInStockInfo = res.data.rows[0]
			data.wmsInstockDs = res.data.rows[0].returnDetail
			data.sumQty = data.wmsInstockDs.sumQty
			watcShowscanList() // 去手动调取计算监属性
		} else {
			uni.showToast({ title: res.message, icon: "none" });
			//navigateBack()
		}
	})
}
const rowClick = (e) => {
	console.log(e)
}
// 查看
const customBtnFn = (item, index) => {
	data.wmsReceiptDsInfo = item
	try {
		let inputParameter = JSON.stringify(item)
		let returnParameter = '无'
		let operationPicture = '采购退料'
		let callInterface = '无'
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: '无',//返回状态
			errorMessage: '无',//错误信息
			isPass: 'Y',//是否成功 Y N
			operationType: OPERATION_LOOK
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
	}
	popup.value.open()
}
const closePopup = () => {
	popup.value.close()
}
// 当前扫描信息关闭  清除当前扫描的信息
const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close();
}
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let repetitionBool = false // 是否重复标识
	let tepList = toRaw(data.scanList)
	tepList.forEach(x => {
		if (code == x.barcode) {
			repetitionBool = true
			uni.showToast({ title: t('JsInternational.scanInputBarcode'), icon: "none" });
			return
		}
	});
	if (repetitionBool) return // 重复扫描 不执行以下流程
	data.scanValue = code
	let parmes = {
		barcode: code,
		isSp: 'N',
		selectType: 'purchaseReturn',
		poCode: data.poCode == 'null' ? '' : data.poCode,
		voCode: data.voCode == 'null' ? '' : data.voCode,
	}
	wmsSelectWmsBarcodeInfo(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			let bool = data.wmsInstockDs.some((item) => {
				return item.materialCode == res.data.materialCode
			})
			if (!bool) {
				uni.showToast({ title: t('materials.materialIsNot'), icon: "none" });
				return
			}
			data.currentQty = res.data.currentQty
			data.scanInfo = res.data
			//data.scanInfo.currentQtyNum = res.data.currentQty
			//data.scanInfo.currentQty = null
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

// 扫码弹框确认信息
const scanConfirmFn = () => {
	// 退料数量：
	if (!data.scanInfo.currentQty) {
		uni.showToast({ title: t('pageTranslation.pleaseInputTheQty'), icon: "none" });
		return;
	}
	if (Number(data.scanInfo.currentQty) == 0) {
		uni.showToast({ title: t('pageTranslation.qtyReturnedMaterial'), icon: "none" });
		return;
	}
	if (Number(data.scanInfo.currentQty) > Number(data.currentQty)) {
		// t('pageTranslation.theQtyExceed') 
		uni.showToast({ title: t('materials.returnedMaterialsShall'), icon: "none" });
		data.scanInfo.currentQty = data.currentQty
		return
	}
	let wmsqty = 0
	let text = ''
	let scanInfo = data.scanInfo
	// 计算当前物料剩余的扫描容量
	data.wmsInstockDs.forEach((item) => {
		if (item.materialCode == scanInfo.materialCode) {
			wmsqty = Number(item.sumQty)  - Number(item.scanNum)
			text = item.materialName
		}
	})
	if (wmsqty - Number(scanInfo.currentQty) < 0) {
		uni.showToast({ title: t('JsInternational.Scanning') + `${text}` + t('JsInternational.qtyGreaterThan'), icon: "none" });
		return
	}

	if (Number(data.scanInfo.currentQty) > Number(data.sumQty)) {
		// t('pageTranslation.theQtyExceed') 
		uni.showToast({ title: t('materials.returnedMaterialsShallNot'), icon: "none" });
		data.scanInfo.currentQty = data.currentQty
		return
	}
	data.currentScanInfo = data.scanInfo
	console.log(1111)
	console.log(data.currentScanInfo.currentQty)
	store.dispatch('stockManage/SetWmsReturnScanList', data.currentScanInfo)
	inputDialog.value.close();
}
// 生成退料单
const handelCreatOrder = () => {
	if (data.scanList.length == 0) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	let tepData = toRaw(data.scanList)
	let list = sortClass(tepData)
	let receiptBarcodes = []
	list.forEach(x => {
		let item = {
			materialCode: '',//物料code
		}
		x.forEach(k => {
			console.log(k)
			let dict = {
				qty: 0
			}
			// 传递表格行里面的行号
			item.line = data.wmsInstockDs.length == 1 ? data.wmsInstockDs[0].line : data.wmsInstockDs.filter(a=>a.materialCode == k.materialCode)[0].line
				
			console.log(item.line)
			item.materialCode = k.materialCode
			item.barcode = k.barcode//条码barcode
			item.barcodeId = k.id//条码id
			item.qty = Number(k.currentQty)//用户输入的qty
			item.asnNo = k.asnNo || ''
			// item.barcodeInfoVos.push(dict)
		})
		receiptBarcodes.push(item)
	});
	let parmes = {
		isSp: 'N',
		poCode: data.poCode == 'null' ? '' : data.poCode,
		voCode: data.voCode == 'null' ? '' : data.voCode,
		instockCode: data.wmsInStockInfo.instockCode, //收料单code
		inStockBarcodes: receiptBarcodes // 条码信息
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	commitRefund(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			//删除已提交的数据
			store.dispatch('stockManage/resetWmsReturnScanList')
			getRequestData()
			// navigateBack()
			// 返回上一个页面
			setTimeout(() => {
				uni.navigateBack()
			}, 1000)

		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

//导航栏左侧返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('stockManage/resetWmsReturnScanList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
	return true
}
const clickRight = () => {
	navigate({
		url: '/pages/materialManage/purchaseReturnRecord'
	})
}
</script>

<style lang="scss" scoped>
// .card-my{
// 	display: flex;
// 	flex-direction: column;
// }</style>